package com.zhijian.warehouse.manage.util;


import com.zhijian.warehouse.manage.config.Constants;
import com.zhijian.warehouse.manage.exception.BusinessCommonException;
import com.zhijian.warehouse.manage.exception.ValidateException;
import com.zhijian.response.enums.ResponseCodeEnum;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author HCG
 * @version 1.0
 * @date 2022/5/12
 */
public class AnnotationValidationUtils {

    /**
     * 使用hibernate的注解来进行验证
     */
    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();


    /**
     * 功能描述: <br>
     * 〈注解验证参数〉
     *
     * @param obj
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static <T> void validate(T obj) {

        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        // 抛出检验异常
        if (constraintViolations.size() > 0) {

            throw new BusinessCommonException(ResponseCodeEnum.FAILURE.code, constraintViolations.iterator().next().getMessage());
        }
    }

    /**
     * 功能描述: <br>
     * 〈注解验证参数〉
     *
     * @param language
     * @param obj
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static <T> void validate(String language, T obj) {

        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        // 抛出检验异常
        if (constraintViolations.size() > 0) {
            String message = constraintViolations.iterator().next().getMessage();
            //分割下，变成数组
            String[] ary = message.split("\\|");
            if (ary.length < 2) {
                //如果长度为1，说明没有自定义内容
                throw new ValidateException(ResponseCodeEnum.FAILURE.code, ary[0]);
            } else {
                throw new ValidateException(ResponseCodeEnum.FAILURE.code, language.equals(Constants.ZH_CN) ? ary[0] : ary[1]);
            }

        }
    }

}
